3
3
.
.
1
1
.
.
3
3
@
@
G
G
e
e
s
s
t
t
u
u
r
r
e
e
S
S
t
t
a
a
t
t
e
e
I
I
n
n
f
f
o
o
Each Gesture consist of multiple smaller States/Phases/Events.
For instance Long Press Gesture is comprised of following Events: Tap, Hold.
And you might want to react not only to the complete Gesture when it is done but also to its different phases.
For instance when implementing Long Press Gesture you might also want to do something on the initial Tap.
@GestureState Variable is used to keep track of the current phase of the Gesture.
As you go through Long Press Gesture this Variable is set to different values indicating current phase of the Gesture.
On initial Tap it is set to true. And when Long Press Gesture finishes it goes back to false.
Since this is a type of State Variable, any it gets changed by the gesture View is redrawn.
In the below code
when we Tap on the Text first we change Opacity (longPressTap = true set Opacity)
and at the end of the Gesture we change Scale (longPressTap = false clears Opacity)
This is achieved through .updating Modifier which sets Variable longPressTap to in-out parameter state.
By settings state to currentState we are effectively forwarding currentState to longPressTap.
During the execution of the Long Press Gesture, updating method is called with three parameters
currentState parameter holds current state of the gesture.
For Long Press Gesture, true value indicates that a tap is detected and false that it ended.
state is in-out parameter that points to the first parameter longPressTap
In the code we set the value of state to currentState which effectively stores this value into longPressTap
transaction parameter stores the context of the current state-processing update.
Example
struct ContentView: View {
@State private var isPressed = false
@GestureState private var longPressTap = false
var body: some View {
Text("HELLO")
.opacity(longPressTap ? 0.4 : 1.0)
.scaleEffect(isPressed ? 5 : 1)
.animation(.easeInOut)
.gesture( LongPressGesture(minimumDuration: 1, maximumDistance: 1)
.updating($longPressTap, body: { (currentState, state, transaction) in
state = currentState
})
.onEnded( { _ in
self.isPressed.toggle()
})
)
}
}
On Tap we change Opacity After Long Press finishes we change Scale